package bean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderableOp;
import javax.media.jai.RenderedOp;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class MemberDTO {

	private MemberVO vo = null;
	private Connection conn = null;

	// 페이지와 관련된 변수

	int listSize = 10; // 페이지당 표시되는 행수
	int blockSize = 3; // 힌블럭당 포시되는 페이지수
	int totSize = 0; // 전체 게시물
	int totPage = 0; // 전체 페이지수
	int totBlock = 0; // 전체 블럭수
	int nowPage = 1; // 현재 페이지
	int nowBlock = 1; // 현재 블럭
	int startNo = 0; // 리스트 목록의 시작 위치
	int endNo = 0; // 리스트 목록의 끝 위치
	int startPage = 0; // 현재 블럭에서 표시되는 시작 블럭번호
	int endPage = 0; // 현재 블럭에서 표시되는 끝 블럭 번호

	public MemberDTO() {
		conn = new MyOracle().getConn();
	}

	public void page() {
		String sql = "select count(*) cnt " + "from member "
				+ "where rno like ? or mid like ?";

		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			ResultSet rs = pst.executeQuery();
			if (rs.next()) {
				totSize = rs.getInt("cnt");
				// 전체 페이지
				totPage = (int) Math.ceil(totSize * 1.0 / listSize);
				// 전체 블럭수
				totBlock = (int) Math.ceil(totPage * 1.0 / blockSize);
				// 현재 블럭
				nowBlock = (int) Math.ceil(nowPage * 1.0 / blockSize);

				// 페이지의 시작과 끝 번호
				endPage = nowBlock * blockSize;
				startPage = endPage - blockSize + 1;
				// 게시물의 시작번호와 끝 번호
				endNo = nowPage * listSize;
				startNo = endNo - listSize + 1;

				// endPage, endNo 보정 값
				if (endPage > totPage) {
					endPage = totPage;
				}
				if (endNo > totSize) {
					endNo = totSize;
				}
				if (startNo < 1) {
					nowBlock = 1;
					startPage = 1;
					endPage = 5;
					endNo = 10;
					startNo = 1;
				}
			}

			System.out.println("<li>totSize = " + totSize);
			System.out.println("<li>totPage = " + totPage);
			System.out.println("<li>totBlock = " + totBlock);

			System.out.println("<li>nowBlock = " + nowBlock);

			System.out.println("<li>startPage = " + startPage);
			System.out.println("<li>endPage = " + endPage);

			System.out.println("<li>endNo = " + endNo);
			System.out.println("<li>startNo = " + startNo);

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public ArrayList<MemberVO> select() { // 검색과 리스트를 위한 처리
		page();
		ArrayList<MemberVO> al = new ArrayList<MemberVO>();
		String sql = "	select * from( " + "	select rownum rn, c.* from( "
				+ "		select * " + "		from member "
				+ "		where rno like ? or mid like ?" + "	)c " + ")b "
				+ " where b.rn between ? and ?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setInt(3, startNo);
			pst.setInt(4, endNo);

			ResultSet rs = pst.executeQuery();
			while (rs.next()) {

				MemberVO v = new MemberVO();
				v.setRno(rs.getInt("rno"));
				v.setMid(rs.getString("mid"));
				v.setIrum(rs.getString("irum"));
				v.setNickname(rs.getString("nickname"));
				v.setPwd(rs.getString("pwd"));
//				v.setImages(rs.getString("images"));
				v.setPhone(rs.getString("phone"));
				v.setEmail(rs.getString("email"));
				v.setBirth(rs.getString("birth"));
				v.setGender(rs.getString("gender"));
				v.setMarry(rs.getString("marry"));
				v.setJob(rs.getString("job"));
				v.setAddress(rs.getString("address"));
				v.setZipcode(rs.getString("zipcode"));
				v.setQuestion(rs.getString("question"));
				v.setAnswer(rs.getString("answer"));
				v.setPriv(rs.getString("priv"));

				al.add(v);
			}
			rs.close();
			pst.close();
			conn.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return al;
	}

	public MemberVO selectOne(){			// view를 위한 처리 
		MemberVO v = new MemberVO();
		String sql = "select * from member where rno=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getRno());
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				v.setRno(rs.getInt("rno"));
				v.setMid(rs.getString("mid"));
				v.setIrum(rs.getString("irum"));
				v.setNickname(rs.getString("nickname"));
				v.setPwd(rs.getString("pwd"));
				v.setImages(rs.getString("images"));
				v.setPhone(rs.getString("phone"));
				v.setEmail(rs.getString("email"));
				v.setBirth(rs.getString("birth"));
				v.setGender(rs.getString("gender"));
				v.setMarry(rs.getString("marry"));
				v.setJob(rs.getString("job"));
				v.setAddress(rs.getString("address"));
				v.setZipcode(rs.getString("zipcode"));
				v.setQuestion(rs.getString("question"));
				v.setAnswer(rs.getString("answer"));
				v.setPriv(rs.getString("priv"));
				
			}
			rs.close();
			pst.close();
			conn.close();
		} catch (Exception e) {

		}
		return v;
	}

	public boolean modify(){         // 9. 수정을 위한 처리 
	      boolean b=false;
	      String sql = 	"update member "
	    		  		+	" set PWD=?, IRUM=?, PHONE=?, BIRTH=?, ADDRESS=?, "
	    		  		+	" GENDER=?, MARRY=?, NICKNAME=?, JOB=?, EMAIL=?, PRIV=?, "
	    		  		+	" QUESTION=?, ANSWER=?, ZIPCODE=?, IMAGES=?"
	    		  		+  " where mid=?";
	      try {
	         PreparedStatement pst =conn.prepareStatement(sql);
	         pst.setString(1, vo.getPwd());
	         pst.setString(2, vo.getIrum());
	         pst.setString(3, vo.getPhone());
	         pst.setString(4, vo.getBirth());
	         pst.setString(5, vo.getAddress());
	         pst.setString(6, vo.getGender());
	         pst.setString(7, vo.getMarry());
	         pst.setString(8, vo.getNickname());
	         pst.setString(9, vo.getJob());
	         pst.setString(10, vo.getEmail());
	         pst.setString(11, vo.getPriv());
	         pst.setString(12, vo.getQuestion());
	         pst.setString(13, vo.getAnswer());
	         pst.setString(14, vo.getZipcode());
	         pst.setString(15, vo.getImages());
	         pst.setString(16, vo.getMid());
	         int cnt = pst.executeUpdate();
	         if (cnt>0) b=true;
	         
	         pst.close();
	         conn.close();
	            
	      } catch (Exception e) {
	         e.printStackTrace();
	      }
	      return b;
	   }
	
	public boolean delete() {
		boolean b = false;

		String sql = "delete from member where rno=?";

		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getRno());

			int cnt = pst.executeUpdate();

			if (cnt > 0) {
				b = true;
				String saveDir = "D:/jhta/workspace_java/webtest/WebContent/src/memberImages";

				File f = new File(saveDir + vo.getImages());
				if (f.exists()) {
					f.delete();
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return b;
	}

	public boolean insert() { // 입력을 위한 처리
		boolean b = false;

		String sql = "insert into member(rno, mid, pwd, irum, phone, birth, address, gender, marry, nickname, job, email, priv, question, answer, zipcode, images) "
				+ "values(seq_member.nextval, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			pst.setString(2, vo.getPwd());
			pst.setString(3, vo.getIrum());
			pst.setString(4, vo.getPhone());
			pst.setString(5, vo.getBirth());
			pst.setString(6, vo.getAddress());
			pst.setString(7, vo.getGender());
			pst.setString(8, vo.getMarry());

			pst.setString(9, vo.getNickname());
			pst.setString(10, vo.getJob());
			pst.setString(11, vo.getEmail());
			pst.setString(12, vo.getPriv());
			pst.setString(13, vo.getQuestion());
			pst.setString(14, vo.getAnswer());
			pst.setString(15, vo.getZipcode());
			pst.setString(16, vo.getImages());

			int cnt = pst.executeUpdate();
			if (cnt > 0)
				b = true;
			pst.close();
			conn.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}

	public boolean login() {
		boolean bolean = false;

		try {

			String sql = "select mid, pwd from member where mid=? and pwd=?";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getMid());
			pst.setString(2, vo.getPwd());

			ResultSet rs = pst.executeQuery();
			if (rs.next()) {
				bolean = true;
			}
			pst.close();
			conn.close();
		} catch (Exception e) {

		}
		return bolean;
	}

	public MemberVO getVo() {
		return vo;
	}

	public void setVo(MemberVO vo) {
		this.vo = vo;
		this.nowPage = vo.getNowPage();
		this.nowBlock = vo.getNowBlock();
	}

	public void fileUpLoad(MemberVO vo2) {
		this.vo = vo2;

		int size = 1024 * 1024 * 10;
		String saveDir = "D:/jhta/workspace_java/webtest/WebContent/src/memberImages";
		String oriFile = "";
		String sysFile = "";

		MultipartRequest multi = null;
		try {
			multi = new MultipartRequest(vo.getRequest(), saveDir, size,
					"utf-8", new DefaultFileRenamePolicy());

			Enumeration files = multi.getFileNames();
			String tempFile = (String) files.nextElement();
			oriFile = multi.getOriginalFileName(tempFile);
			sysFile = multi.getFilesystemName(tempFile);

			vo.setMid(multi.getParameter("mid"));
			vo.setIrum(multi.getParameter("irum"));
			vo.setPwd(multi.getParameter("pwd"));
			vo.setImages(sysFile);
			vo.setPhone(multi.getParameter("phone"));
			vo.setBirth(multi.getParameter("birth"));
			vo.setAddress(multi.getParameter("address"));
			vo.setGender(multi.getParameter("gender"));
			vo.setMarry(multi.getParameter("marry"));
			vo.setNickname(multi.getParameter("nickname"));
			vo.setJob(multi.getParameter("job"));
			vo.setEmail(multi.getParameter("email"));
			vo.setQuestion(multi.getParameter("question"));
			vo.setAnswer(multi.getParameter("answer"));
			vo.setZipcode(multi.getParameter("zipcode"));
			vo.setPriv(multi.getParameter("priv"));
			vo.setPriv(multi.getParameter("rno"));

			 // 섬 네일 파일 추가 생성
			 ParameterBlock pd = new ParameterBlock();			 
			 pd.add(saveDir + sysFile);
			 /* ParameterBlock 클래스에 변환할 이미지를 담고 그 이미지를 불러온다.
			    saveDir = "D:/jhta/workspace_java/webtest/WebContent/src/memberImages";
			    sysFile = ""; */
			 
			 RenderedOp rop = JAI.create("fileload", pd);
			 
			 BufferedImage bi = rop.getAsBufferedImage();
			 // 불러온 이미지를 bi로 생성한 BufferedImage 클래스에 담는다.
			 
			 BufferedImage thumb = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
			 // thumb이라는 이미지 버퍼를 생성하고 버퍼 크기를 100 x 100으로 설정한다.
			 
			 Graphics2D g = thumb.createGraphics();
			 g.drawImage(bi, 0, 0, 100, 100, null);
			 // thumb의 이미지 버퍼에 원본 이미지를 정해진 버퍼 사이즈인 100 x 100으로 맞추어 드로우한다.
			 
			 File file = new File(saveDir + "/sm_" + sysFile);
			 ImageIO.write(thumb, "jpg", file);
			 // 출력위치·파일이름 설정, 섬네일 이미지 생성, 파일 유형 jpg 설정
			 
			// db에 저장
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public MemberVO getVo2() {
		return vo;
	}

	public int getListSize() {
		return listSize;
	}

	public void setListSize(int listSize) {
		this.listSize = listSize;
	}

	public int getBlockSize() {
		return blockSize;
	}

	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}

	public int getTotSize() {
		return totSize;
	}

	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}

	public int getTotPage() {
		return totPage;
	}

	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}

	public int getTotBlock() {
		return totBlock;
	}

	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}

	public int getNowPage() {
		return nowPage;
	}

	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}

	public int getNowBlock() {
		return nowBlock;
	}

	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public int getEndPage() {
		return endPage;
	}

	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
}
